﻿using Labthink.PCSoft.UniversalHost4.ControlInterface;
using Labthink.PCSoft.UniversalHost4.Model;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class LoginStatus
    {
        private readonly TileMenu _menuWindow = new TileMenu();

        public string UserName
        {
            get => (string)GetValue(UserNameProperty);
            set => SetValue(UserNameProperty, value);
        }

        public static readonly DependencyProperty UserNameProperty =
            DependencyProperty.Register(nameof(UserName), typeof(string), typeof(LoginStatus), new PropertyMetadata(null));

        public Visibility ShowMenu
        {
            get => (Visibility)GetValue(ShowMenuProperty);
            set => SetValue(ShowMenuProperty, value);
        }

        public static readonly DependencyProperty ShowMenuProperty =
            DependencyProperty.Register(nameof(ShowMenu), typeof(Visibility), typeof(LoginStatus), new PropertyMetadata(Visibility.Visible));

        public Control ParentControl { get; set; }

        public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
            "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(LoginStatus));

        public event RoutedEventHandler Tap
        {
            add => AddHandler(TapEvent, value);
            remove => RemoveHandler(TapEvent, value);
        }

        private void SignalParent(object sender, System.Windows.RoutedEventArgs e)
        {
            this.RaiseEvent(new RoutedEventArgs(TapEvent, this));
        }

        public LoginStatus()
        {
            InitializeComponent();
        }

        private void BtnUserSetting_OnClick(object sender, RoutedEventArgs e)
        {
            _menuWindow.ParentControl = ParentControl;
            _menuWindow.ShowDialog();
        }

        private void LoginStatus_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                UserName = "test user";
                return;
            }

            var c = ParentControl as IPart;

            for (int i = c.MenuItems.Items.Count - 1; i >= 0; i--)
            {
                var item = c.MenuItems.Items[i];
                c.MenuItems.Items.Remove(item);
                if (!(item is TileMenuItem menu))
                {
                    continue;
                }

                if (menu.Group == MenuGroup.Instrument)
                {
                    _menuWindow.InstrumentMenus.Add(new TileMenuItem { Title = menu.Title, WindowType = menu.WindowType });
                }
                else if (menu.Group == MenuGroup.System)
                {
                    _menuWindow.SystemMenus.Add(new TileMenuItem { Title = menu.Title, WindowType = menu.WindowType });
                }
            }
        }
    }
}
